//
//  MessageDetailTableViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/15.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "MessageDetailTableViewController.h"
#import "MessageToolbar.h"
#import "UUMessage.h"
#import "UUMessageFrame.h"
#import "UUMessageCell.h"
#import "Puser.h"
#import <MJRefresh.h>
#import "MessageMode.h"
#import "PersonalDetailViewController.h"
#import "CompanyDetailViewController.h"
#import <IQKeyboardManager.h>
@interface MessageDetailTableViewController ()<UITableViewDataSource,UITableViewDelegate,MessageToolBarDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UUMessageCellDelegate>{
    BOOL isshow;
}
@property (nonatomic,strong) MessageToolbar *toolbar;
@property (nonatomic,strong) UITableView *tablview;
@property (nonatomic,strong) NSMutableArray *messagearray;
@property (nonatomic,strong) Puser *user;
@property (nonatomic,strong) NSMutableArray *sendingArray;
@property (nonatomic,strong) UIImagePickerController *picker;

@end

@implementation MessageDetailTableViewController
-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}
-(NSMutableArray *)sendingArray{
    if ( _sendingArray==nil) {
        _sendingArray=[NSMutableArray array];
    }
    return  _sendingArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=bgGarycolor;
     [self.tablview.header beginRefreshing];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    if ([self.toid integerValue]!=28) {
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"top-r-one"] style:UIBarButtonItemStyleDone target:self action:@selector(rightclick)];
    }
    [self setupTablView];
    [self setupToolbar];
    [self setupdata];
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    

     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardshow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardhide:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)keyboardshow:(NSNotification *)notice{
    NSLog(@"----------%@",notice);
    
   
    
    CGFloat height = [notice.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
//    CGFloat duration = [notice.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.tablview.height=XHScreenheight-height;
        self.toolbar.y=XHScreenheight-44-height;
    }];
    [self tableViewScrollToBottom];

}

-(void)keyboardhide:(NSNotification *)notice{
    
    [UIView animateWithDuration:0.3 animations:^{
        self.tablview.height=XHScreenheight;
        self.toolbar.y=XHScreenheight-44;
    }];

}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    
    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    
    NSDictionary *content=extras[@"content"];
    [UUMessage setupReplacedKeyFromPropertyName:^NSDictionary *{
        return @{
                 @"ID":@"id"
                 
                 };
    }];

    UUMessage *message=[UUMessage objectWithKeyValues:content];
     if (message.fromId==self.toid) {
    UUMessageFrame *meessagef=[[UUMessageFrame alloc]init];
    
    int power=[self.user.power intValue];
    if ([message.fromId integerValue]==[self.toid integerValue]&&[message.fromType integerValue]==[self.totype integerValue]) {
        message.from=UUMessageFromOther;
        message.strName=self.navigationItem.title;
        message.strIcon=[NSString getImageURLstr:self.toico];
    }else{
        message.from=UUMessageFromMe;
        message.strIcon=power<5?[NSString getImageURLstr:self.user.user_ico]:[NSString getImageURLstr:self.user.com_ico];
        message.strName=power<5?self.user.user_truename:self.user.com_name;
    }
    if (message.imgs) {
        message.type=UUMessageTypePicture;
        message.picurl=[NSString getImageURLstr:message.imgs];
    }else{
        message.type=UUMessageTypeText;
        message.strContent=message.content;
    }
    message.strTime=message.sendtime;
    meessagef.message=message;
    meessagef.state=SENDSUSSTATE;
   
    [self.messagearray addObject:meessagef];
    
    [self.tablview reloadData];
    [self tableViewScrollToBottom];
         [self updatconut];
     }else{
         
     }
    
}
-(void)cellRenturnpostClick:(UUMessageCell *)cell{
    NSIndexPath *indexpath=[self.tablview indexPathForCell:cell];
   UUMessageFrame *messageframe= self.messagearray[indexpath.row];
    [self postmessage:messageframe];
    
}

-(UIImagePickerController *)picker{
    if (_picker==nil) {
        _picker=[[UIImagePickerController alloc]init];
        _picker.view.backgroundColor = [UIColor whiteColor];
        _picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
        _picker.delegate =self;
        _picker.allowsEditing = YES;
    }
    return _picker;
}


-(void)clickWithTag:(NSInteger)index{
    if (index==1) {
        if (self.toolbar.messagetext.text.length>0) {
            UUMessageFrame *messagef=[[UUMessageFrame alloc]init];
            UUMessage *message=[[UUMessage alloc]init];
            message.from=UUMessageFromMe;
            message.strContent=self.toolbar.messagetext.text;
            message.type=UUMessageTypeText;
            NSInteger power=[self.user.power integerValue];
            message.strIcon=power<5?[NSString getImageURLstr:self.user.user_ico]:[NSString getImageURLstr:self.user.com_ico];
            
            NSDate *datenow=[NSDate date];
           
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            
            message.strTime=[dateFormatter stringFromDate:datenow];
            messagef.message=message;
            messagef.state=SENDLOADINGSTATE;
            [self.messagearray addObject:messagef];
            [self.tablview reloadData];
            [self tableViewScrollToBottom];
            [self.sendingArray addObject:messagef];
            [self postmessage:messagef];
            
            
        }
    }else if(index==0){
        [self presentViewController:self.picker animated:YES completion:nil];

    }
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [self dismissViewControllerAnimated:YES completion:^{
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        UUMessageFrame *messagef=[[UUMessageFrame alloc]init];
        UUMessage *message=[[UUMessage alloc]init];
        message.from=UUMessageFromMe;
        message.picture=image;
        message.type=UUMessageTypePicture;
        NSInteger power=[self.user.power integerValue];
        message.strIcon=power<5?[NSString getImageURLstr:self.user.user_ico]:[NSString getImageURLstr:self.user.com_ico];
        NSDate *datenow=[NSDate date];
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        
        message.strTime=[dateFormatter stringFromDate:datenow];
        messagef.message=message;
        messagef.state=SENDLOADINGSTATE;
        [self.messagearray addObject:messagef];
        [self.tablview reloadData];
        [self tableViewScrollToBottom];
        [self postmessage:messagef];

        
    }];

}

-(void)postmessage:(UUMessageFrame *)messagef{
    self.toolbar.messagetext.text=nil;
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"send_news";
     NSInteger power=[self.user.power integerValue];
    if (power<5) {
        params[@"from_id"]=self.user.user_id;
        params[@"from_type"]=@"1";
    }else{
        params[@"from_id"]=self.user.com_id;
        if (power==8) {
            params[@"from_type"]=@"3";
        }else if (power==10){
            params[@"from_type"]=@"4";
        }
        
        else{
        params[@"from_type"]=@"2";
        }
    }
    if (messagef.message.type==UUMessageTypePicture) {
        NSData *imagedata=[UIImage compressData:messagef.message.picture toMaxFileSize:DefailutPicSize];
        NSString *base64str=[imagedata imageBase64Data:imagedata];
        params[@"content"]=base64str;
        
    }else{
    
    params[@"content"]=messagef.message.strContent;
    }
   
    params[@"to_id"]=self.toid;
    params[@"to_type"]=self.totype;
    
    
   [PostUitls Post:messageurl parameters:params success:^(id response) {
       NSDictionary *dict=response;
       NSNumber *state=dict[@"data"];
       if ([state integerValue]>0) {
           messagef.message.ID=[state stringValue];
           
           messagef.state=SENDSUSSTATE;
       }else{
           messagef.state=SENDFAILSTATE;
       }
       NSInteger indext=[self.messagearray indexOfObject:messagef];
       
       NSIndexPath *indexpath=[NSIndexPath indexPathForRow:indext inSection:0];
//       [self tableViewScrollToBottom];
       [self.tablview reloadRowsAtIndexPaths:@[indexpath] withRowAnimation:UITableViewRowAnimationAutomatic];
       
       
   } failure:^(NSError *error) {
       messagef.state=SENDFAILSTATE;
       NSInteger indext=[self.messagearray indexOfObject:messagef];
       
       NSIndexPath *indexpath=[NSIndexPath indexPathForRow:indext inSection:0];
       //       [self tableViewScrollToBottom];
       [self.tablview reloadRowsAtIndexPaths:@[indexpath] withRowAnimation:UITableViewRowAnimationAutomatic];
//       [self.tablview reloadData];
//       [self tableViewScrollToBottom];
   }];
    
    
}

//tableView Scroll to bottom
- (void)tableViewScrollToBottom
{
    if (self.messagearray.count==0)
        return;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.messagearray.count-1 inSection:0];
    [self.tablview scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}


-(void)rightclick{
    if ([self.totype integerValue]==1) {
        PersonalDetailViewController *pvc=[PersonalDetailViewController viewcontroller];
        pvc.user_id=self.toid;
        [self.navigationController pushViewController:pvc animated:YES];
    }else{
        CompanyDetailViewController *cvc=[CompanyDetailViewController viewcontroller];
        cvc.com_id=self.toid;
        cvc.user_type=self.totype;
        [self.navigationController pushViewController:cvc animated:YES];
    }
}



-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}
     ];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbg"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTranslucent:YES];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
}
-(NSMutableArray *)messagearray{
    if (_messagearray==nil) {
        _messagearray=[NSMutableArray array];
    }
    return _messagearray;
}
-(void)setupdata{
    
    if (self.array.count>0) {
        
    }else{
        
    }

}


-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
   
}

-(void)setupTablView{
    UITableView *tablview=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, XHScreenwidth, XHScreenheight) style:UITableViewStylePlain];
    tablview.delegate=self;
    tablview.dataSource=self;
    tablview.separatorStyle=UITableViewCellSeparatorStyleNone;
    tablview.backgroundColor=[UIColor clearColor];
    self.tablview=tablview;
    self.tablview.contentInset=UIEdgeInsetsMake(0, 0, 44, 0);
    [self.view addSubview:tablview];
    [self updatconut];
    MJRefreshNormalHeader *header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tablview.header=header;
    self.tablview.header.automaticallyChangeAlpha=YES;
    [self.tablview.header beginRefreshing];
   
}
-(void)updatconut{
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"read_news";
    params[@"to_id"]=self.toid;
    params[@"to_type"]=self.totype;
    NSInteger power=[self.user.power integerValue];
    if (power<5) {
        params[@"from_id"]=self.user.user_id;
        params[@"from_type"]=@"1";
    }else{
        params[@"from_id"]=self.user.com_id;
        if (power==8) {
            params[@"from_type"]=@"3";
        }else{
            params[@"from_type"]=@"2";
        }
    }
   [PostUitls Post:messageurl parameters:params success:^(id response) {
       
   } failure:^(NSError *error) {
       
   }];
}

-(void)refresh{
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"from_id"]=self.toid;
    params[@"from_type"]=self.totype;
    NSInteger power=[self.user.power integerValue];
    if (power<5) {
        params[@"to_id"]=self.user.user_id;
        params[@"to_type"]=@"1";
    }else{
        params[@"to_id"]=self.user.com_id;
        if (power==8) {
            params[@"to_type"]=@"3";
        }else if (power==10){
            params[@"to_type"]=@"4";
        }        
        else{
            params[@"to_type"]=@"2";
        }
    }
   params[@"action"]=@"newslist";
    BOOL loadmore=NO;
    if (self.messagearray.count>0) {
        NSMutableArray *Idarray=[NSMutableArray array];
        for (UUMessageFrame *messagef in self.messagearray) {
            [Idarray addObject:messagef.message.ID];
        }
        params[@"page_id"]=[NSString DataTOjsonString:Idarray];
        loadmore=YES;
    }
    
    [PostUitls Post:messageurl parameters:params success:^(id response) {
        
       
        NSDictionary *dict=response;
        [UUMessage setupReplacedKeyFromPropertyName:^NSDictionary *{
            return @{
            @"ID":@"id"
            
            };
        }];
        
        NSArray *array=[UUMessage objectArrayWithKeyValuesArray:dict[@"data"]];
        NSMutableArray *marray=[NSMutableArray array];
        for (UUMessage *message in array) {
            UUMessageFrame *messagef=[[UUMessageFrame alloc]init];
            if ([message.fromId integerValue]==[self.toid integerValue]&&[message.fromType integerValue]==[self.totype integerValue]) {
                message.from=UUMessageFromOther;
                message.strIcon=[NSString getImageURLstr:self.toico];
               
            }else{
                message.from=UUMessageFromMe;
                int power=[self.user.power intValue];
                if (power<5) {
                      message.strIcon=[NSString getImageURLstr:self.user.user_ico];
                }else{
                     message.strIcon=[NSString getImageURLstr:self.user.com_ico];
                }
            
            }
            if (message.imgs) {
                message.type=UUMessageTypePicture;
                message.picurl=[NSString getImageURLstr:message.imgs];
            }else{
                message.type=UUMessageTypeText;
                message.strContent=message.content;
            }
           
            message.strTime=message.sendtime;
            messagef.message=message;
            messagef.state=SENDSUSSTATE;
            [marray addObject:messagef];
           
            
        }
        
        NSInteger oldCnt = [self.messagearray count];
    
        

        
        
        NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:
                               NSMakeRange(0,[marray count])];
         [self.messagearray insertObjects:marray atIndexes:indexes];
          NSInteger newCnt  = [self.messagearray count];
        [self.tablview.header endRefreshing];
        [self.tablview reloadData];
        if (!loadmore) {
             [self tableViewScrollToBottom];
        }else{
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:newCnt - oldCnt inSection:0];
          [self.tablview scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
        }

    } failure:^(NSError *error) {
        
    }];
   
}
-(void)setupToolbar{
    MessageToolbar *toolbar=[MessageToolbar toolbar];
    [self.view addSubview:toolbar];
    [self.view bringSubviewToFront:toolbar];
    self.toolbar=toolbar;
    toolbar.delegate=self;
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.toolbar.messagetext endEditing:YES];
    
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.toolbar.messagetext endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return self.messagearray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UUMessageCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell==nil) {
        cell=[[UUMessageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    
    }
    UUMessageFrame *frame= self.messagearray[indexPath.row];
    cell.messageFrame=frame;
    cell.delegate=self;
    if (frame.state==SENDLOADINGSTATE) {
        [cell.indicator startAnimating];
    }else{
        if (frame.state==SENDFAILSTATE) {
            cell.repostbtn.hidden=NO;
        }else{
            cell.repostbtn.hidden=YES;
        }
        [cell.indicator stopAnimating];
    }

    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UUMessageFrame  *messagef= self.messagearray[indexPath.row];
    return messagef.cellHeight;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
